<template>
  <div class="common-container">
    <el-breadcrumb separator="/" class="common_breadcrumb">
      <el-breadcrumb-item @click="handleBack">数据集</el-breadcrumb-item>
      <el-breadcrumb-item>API</el-breadcrumb-item>
    </el-breadcrumb>
    <el-form :inline="true"
             :label-width="80"
             label-placement="left"
             :model="query"
             size="small">
      <el-form-item label="名称:" prop="name">
        <el-input placeholder="请输入API名称" v-model="query.name" @keyup.enter.native="getMyAPIList"
                  clearable
                  @change="getMyAPIList"/>
      </el-form-item>
      <el-form-item label="请求类型:" prop="methods">
        <el-input placeholder="请输入请求类型" v-model="query.methods"
                  clearable
                  @change="getMyAPIList"/>
      </el-form-item>
      <el-form-item label="请求地址" prop="server">
        <el-input placeholder="请输入请求地址" v-model="query.server" @keyup.enter.native="getMyAPIList"
                  clearable
                  @change="getMyAPIList"/>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input placeholder="请输入备注" v-model="query.remark" @keyup.enter.native="getMyAPIList"
                  clearable
                  @change="getMyAPIList"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getMyAPIList">
          <el-icon style="vertical-align: middle;">
            <Search></Search>
          </el-icon>
          <span style="vertical-align: middle;">查询</span>
        </el-button>
        <el-button type="success"
                   @click="handleModalAddAction">
          <el-icon style="vertical-align: middle;">
            <CirclePlus></CirclePlus>
          </el-icon>
          <span style="vertical-align: middle;">新增</span>
        </el-button>
      </el-form-item>
    </el-form>

    <el-table :data="apiList" border style="width: 100%" v-loading="apiLoading">
      <el-table-column type="index" width="50" title="序号"/>
      <el-table-column property="name" align="center" label="名称"/>
      <el-table-column align="center" property="server" label="请求地址"/>
      <el-table-column property="methods" align="center" label="请求类型">
        <template #default="scope">
          <el-tag effect="dark" size="small" :type="showType(scope.row.methods)">{{ scope.row.methods }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" property="remark" label="备注"/>
      <el-table-column align="center" property="create_timestamp" label="创建时间"/>
      <el-table-column align="center" label="操作">
        <template #default="scope">
          <el-button size="mini" type="success" @click="handleModalEditAction(scope.row)">更新</el-button>
          <el-button size="mini" type="danger" plain @click="handleModalDelAction(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        class="common-pagination"
        v-model:currentPage="pagination.page"
        :page-size="pagination.size"
        layout="prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    >
    </el-pagination>
    <el-drawer
        v-model="APIOpModel"
        :title="modalTitle[modalStatus]"
        size="28%"
        direction="rtl">
      <el-form
          :model="apiForm"
          :rules="rules"
          ref="apiFormRef"
          label-placement="left"
          label-width="80px"
          size="small">
        <el-form-item label="名称:" prop="name">
          <el-input placeholder="请输入名称" v-model="apiForm.name" clearable @change="handleFormChange"/>
        </el-form-item>
        <el-form-item label="请求地址:" prop="server">
          <el-input placeholder="请输入请求地址" v-model="apiForm.server" clearable @change="handleFormChange"/>
        </el-form-item>
        <el-form-item label="请求类型:" prop="methods">
          <el-select placeholder="请选择请求类型" v-model="apiForm.methods"
                     @change="handleFormChange" clearable filterable>
            <el-option
                v-for="item in requestMethodsList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注:" prop="remark">
          <el-input placeholder="请输入备注" type="textarea" clearable v-model="apiForm.remark"/>
        </el-form-item>
        <el-tabs v-model="tabName" type="card">
          <el-tab-pane label="Params" name="Params">
            <n-dynamic-input
                preset="pair"
                v-model="apiForm.Params"
                @change="handleFormChange"
                key-placeholder="key"
                value-placeholder="value"
            />
          </el-tab-pane>
          <el-tab-pane label="Headers" name="Headers">
            <n-dynamic-input
                preset="pair"
                v-model="apiForm.Headers"
                @change="handleFormChange"
                key-placeholder="key"
                value-placeholder="value"
            />
          </el-tab-pane>
          <el-tab-pane label="Body" name="Body">
            <n-dynamic-input
                preset="pair"
                v-model="apiForm.Body"
                @change="handleFormChange"
                key-placeholder="key"
                value-placeholder="value"
            />
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div class="footer-modal">
        <el-button @click="handleCloseModal" size="small" class="footer-modal--btn">取消</el-button>
        <el-button type="primary" size="small" class="footer-modal--btn"
                   v-loading="formLoading"
                   @click="handleTestAPI">测试
        </el-button>
        <el-button v-if="modalStatus ==='add'" type="primary" size="small"
                   v-loading="formLoading"
                   class="footer-modal--btn base-primary-btn m_lr_10"
                   :disabled="!submitFlag"
                   @click="handleAddAPI">确认
        </el-button>
        <el-button v-if="modalStatus ==='edit'" type="primary" size="small"
                   v-loading="formLoading"
                   class="footer-modal--btn base-primary-btn m_lr_10"
                   :disabled="!submitFlag"
                   @click="handleEditAPI">更新
        </el-button>
      </div>
    </el-drawer>
    <el-dialog v-model="checkModal" title="测试结果" width="50%" destroy-on-close>
      <my-monaco-editor language="json"
                        :height="500"
                        :code="requestData"
                        :auto-format="true"></my-monaco-editor>
      <template #footer>
        <el-button @click="handleCloseModal" plain size="small" class="footer-modal--btn">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { defineComponent, onMounted, ref } from "vue";
// import { NDynamicInput, } from "naive-ui";
import { addDataAPI, delDataAPI, editDataAPI, getDataAPIList, testDataAPI } from "../../../service/data_api";
import { useRouter } from "vue-router";
import { authTypeList, requestMethodsList, sqlTypeList } from "../../../utils/dict";
import { CirclePlus, Search } from "@element-plus/icons";
import { ElMessage, ElMessageBox } from "element-plus";

export default defineComponent({
  name: "my-data-api",
  components: {
    // NDynamicInput,
    CirclePlus,
    Search,
  },
  setup() {
    const router = useRouter();
    const apiLoading = ref(false);
    const formLoading = ref(false);
    const apiList = ref([]);
    const APIOpModel = ref(false);
    const modalStatus = ref("add");
    const checkModal = ref(false);
    const tabName = ref("Params");
    const total = ref(0);
    const modalTitle = ref({
      add: "新增API",
      edit: "编辑API"
    });
    const requestData = ref("");
    const query = ref({
      limit: 10,
      size: 1,
      name: "",
      methods: "",
      server: "",
      remark: "",
    });
    const handleSizeChange = (pageSize) => {
      query.value.page = 1;
      query.value.size = pageSize;
      getMyAPIList();
    };
    const handleCurrentChange = (page) => {
      query.value.page = page;
      getMyAPIList();
    };
    const pagination = ref({
      page: 1,
      size: 10,
    });
    const apiForm = ref({
      name: undefined,
      remark: undefined,
      server: undefined,
      methods: undefined,
      Params: [],
      Headers: [{ "key": "Content-Type", "value": "application/json" }],
      Body: []
    });
    const apiFormRef = ref(null);
    const submitFlag = ref(false);
    const handleFormChange = () => {
      submitFlag.value = false;
    };
    const resetForm = () => {
      apiForm.value = {
        name: undefined,
        remark: undefined,
        server: undefined,
        methods: undefined,
        Params: [],
        Headers: [{ "key": "Content-Type", "value": "application/json" }],
        Body: []
      };
    };
    const handleModalAddAction = () => {
      resetForm();
      modalStatus.value = "add";
      APIOpModel.value = true;
    };
    const handleCloseModal = () => {
      APIOpModel.value = false;
    };
    const getMyAPIList = () => {
      apiLoading.value = true;
      getDataAPIList(query.value).then(res => {
        apiList.value = res.data.result;
        apiLoading.value = false;
        total.value = res.data.total;
      }).catch(() => {
        apiLoading.value = false;
      });
    };
    const handleTestAPI = () => {
      formLoading.value = true;
      apiFormRef.value.validate((valid) => {
        if (valid) {
          testDataAPI(apiForm.value).then((res) => {
            formLoading.value = false;
            ElMessage({
              type: "success",
              message: "连接API成功"
            });
            checkModal.value = true;
            submitFlag.value = true;
            requestData.value = JSON.stringify(res);
          }).catch(err => {
            formLoading.value = false;
            ElMessage.error("连接API失败");
          });
        }
      });
    };
    const handleAddAPI = () => {
      formLoading.value = true;
      apiFormRef.value.validate((valid) => {
        if (valid) {
          let data = Object.assign({}, apiForm.value, {
            Params: JSON.stringify(apiForm.value.Params),
            Headers: JSON.stringify(apiForm.value.Headers),
            Body: JSON.stringify(apiForm.value.Body)
          });
          addDataAPI(data).then(() => {
            ElMessage({
              type: "success",
              message: "新增API成功"
            });
            formLoading.value = false;
            handleCloseModal();
            getMyAPIList();
          }).catch(err => {
            formLoading.value = false;
            ElMessage.error("新增API失败");
          });
        }
      });
    };
    const handleModalEditAction = (rowData) => {
      resetForm();
      apiForm.value = Object.assign({}, rowData, {
        Params: JSON.parse(rowData.Params),
        Headers: JSON.parse(rowData.Headers),
        Body: JSON.parse(rowData.Body)
      });
      modalStatus.value = "edit";
      submitFlag.value = false;
      APIOpModel.value = true;
    };
    const handleEditAPI = () => {
      formLoading.value = true;
      apiFormRef.value.validate((valid) => {
        if (valid) {
          let data = Object.assign({}, apiForm.value, {
            Params: JSON.stringify(apiForm.value.Params),
            Headers: JSON.stringify(apiForm.value.Headers),
            Body: JSON.stringify(apiForm.value.Body)
          });
          editDataAPI(data).then(() => {
            ElMessage({
              type: "success",
              message: "编辑API成功"
            });
            handleCloseModal();
            getMyAPIList();
            formLoading.value = false;
          }).catch(err => {
            formLoading.value = false;
            ElMessage.success("编辑API失败");
          });
        } else {
          formLoading.value = false;
        }
      });
    };
    const handleModalDelAction = (rowData) => {
      ElMessageBox.confirm(
          `你确定删除 ${rowData.name} 么？`,
          "警告",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
      ).then(() => {
        handleDelAPI(rowData);
      });
    };
    const handleDelAPI = (rowData) => {
      delDataAPI({ data_api_id: rowData.data_api_id }).then(() => {
        ElMessage({
          type: "success",
          message: "删除API成功"
        });
        getMyAPIList();
      }).catch(() => {
        ElMessage.error("删除API失败");
      });
    };
    const handleBack = () => {
      router.push({ path: "index" });
    };
    const handleCheckCloseModal = () => {
      checkModal.value = false;
    };
    const showType = (type) => {
      let tagType;
      switch (type) {
        case "POST":
          tagType = "success";
          break;
        case "GET":
          tagType = "";
          break;
        case "PUT":
          tagType = "info";
          break;
        case "DELETE":
          tagType = "warning";
          break;
        default:
          break;
      }
      return tagType;
    };
    onMounted(() => {
      getMyAPIList();
    });
    return {
      rules: {
        name: {
          required: true,
          trigger: ["blur", "input"],
          message: "请输入API名称",
        },
        methods: {
          required: true,
          message: "请选择API类型",
          trigger: ["change",]
        },
        server: {
          required: true,
          message: "请输入服务器地址",
          trigger: ["input", "blur",]
        },
      },
      query,
      total,
      tabName,
      checkModal,
      apiList,
      APIOpModel,
      apiForm,
      submitFlag,
      apiFormRef,
      modalStatus,
      modalTitle,
      requestData,
      apiLoading,
      formLoading,
      authTypeList,
      requestMethodsList,
      sqlTypeList: sqlTypeList,
      pagination,
      handleSizeChange,
      handleCurrentChange,
      getMyAPIList,
      handleCloseModal,
      handleModalAddAction,
      handleFormChange,
      resetForm,
      handleDelAPI,
      handleModalDelAction,
      handleModalEditAction,
      handleTestAPI,
      handleAddAPI,
      handleEditAPI,
      handleBack,
      handleCheckCloseModal,
      showType,
    };
  }
});
</script>

